package com.javer.web.action;

import java.net.URLDecoder;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.javer.service.CommService;
import com.javer.util.Constants;

@Controller("/comm")
public class CommAction extends DispatchAction {
	final Log logger = LogFactory.getLog(getClass());
	@Autowired private CommService commService;

	public ActionForward deleteById(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		int id = Integer.valueOf(req.getParameter("id"));
		String tableName = req.getParameter("tableName");
		commService.deleteById(tableName, id);
		return null;
	}
	
	public ActionForward deleteByProperty(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String tableName = req.getParameter("tableName");
		String propertyName = req.getParameter("propertyName");
		String propertyValue = req.getParameter("propertyValue");
		propertyValue = URLDecoder.decode(propertyValue, "UTF-8");
		commService.deleteByProperty(tableName, propertyName, propertyValue);
		return null;
	}
	
	// 错误处理
	public ActionForward doError(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		ServletContext ctx = req.getSession().getServletContext();
		AtomicInteger totalErrorCount = (AtomicInteger) ctx.getAttribute(Constants.TotalErrorCount);
		if (totalErrorCount == null) {
			totalErrorCount = new AtomicInteger(0);
			ctx.setAttribute(Constants.TotalErrorCount, totalErrorCount);
		}
		totalErrorCount.incrementAndGet();
		return new ActionForward("/error.jsp", true);
	}
	
	public ActionForward getMapById(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		int id = Integer.valueOf(req.getParameter("id"));
		String tableName = req.getParameter("tableName");
		req.setAttribute("queryResult", commService.getMapById(tableName, id));
		return new ActionForward(req.getParameter("forward"));
	}
	
}
